from django_redis import get_redis_connection
from rest_framework import serializers

from users.models import User
from .models import OAuthQQUser

class OAuthQQUserSerializer(serializers.Serializer):
    access_token = serializers.CharField(label='操作凭证')
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码')
    
    def validate(self, data):
        
        access_token = data.get("access_token")
        openid = OAuthQQUser.check_save_user_token(access_token)
        if not openid:
            raise serializers.ValidationError("无效的access_token")
        
        data['openid'] = openid
        
        mobile = data.get('mobile')
        sms_code = data.get("sms_code")
        redis_conn = get_redis_connection('verify_codes')
        real_sms_code = redis_conn.get("sms_%s" % mobile).decode()
        if real_sms_code != sms_code:
            raise  serializers.ValidationError('短信验证码错误')
        
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            pass
        else:
            password = data.get('password')
            if not user.check_password(password):
                raise serializers.ValidationError("密码错误")
            data['user'] = user
            
        return data
    
    def create(self,validated_data):
        user = validated_data.get('user')
        if not user:
            user = User.objects.create_user(
                username=validated_data['mobile'],
                password=validated_data['password'],
                mobile=validated_data['mobile'],
            )
    
        OAuthQQUser.objects.create(
            openid=validated_data.get('openid'),
            user=user
        )
        return user
        
